﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Prism.Services.Dialogs;
using YJTMedicalAideManage.MAM.ViewModels;

namespace YJTMedicalAideManage.MAM.Services
{
    public class DialogService
    {
        public bool? ShowDialog<TViewModel>(TViewModel viewModel) where TViewModel : class
        {
            var windowType = FindWindowType(viewModel.GetType());
            if (windowType == null) return null;

            var window = (Window)Activator.CreateInstance(windowType);
            window.DataContext = viewModel;

            if (viewModel is INotifyPropertyChanged vm &&
                windowType.GetProperty("DialogResult") != null)
            {
                var closeAction = new Action(() => window.DialogResult = ((dynamic)viewModel).DialogResult);
                ((dynamic)viewModel).CloseAction = closeAction;
            }

            return window.ShowDialog();
        }

        private static Type FindWindowType(Type viewModelType)
        {
            var viewName = viewModelType.FullName.Replace("ViewModel", "View");
            return Assembly.GetExecutingAssembly().GetType(viewName);
        }
    }
}
